package com.soup.lab.basic.proxy;

import org.junit.jupiter.api.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxyTestCase {

    @Test
    public void test() {
        Duck duck = (Duck) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{Duck.class}, new DuckInvocationHandler(new RubberDuck()));
        duck.bark();
    }

    interface Duck {
        void bark();
    }

    static class RubberDuck implements Duck {
        @Override
        public void bark() {
            System.out.println("bia~ bia~");
        }
    }

    static class DuckInvocationHandler implements InvocationHandler {

        public Object target;

        public DuckInvocationHandler(Object target) {
            this.target = target;
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if("bark".equals(method.getName())) {
                System.out.println("Duck is barking...");
            }
            return method.invoke(target, args);
        }
    }

}
